package com.yan.test.work.testpaging3;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.yan.test.work.testpaging3.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding mBinding;
    private DataAdapter2 adapter;
    private MainViewModel viewModel;
    private int from = 0;
    private String keyWord = "Paging3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        setContentView(mBinding.getRoot());
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);
        initView();
        initListener();
        initData();
    }


    private void initView() {
        mBinding.listView.setLayoutManager(new LinearLayoutManager(this , LinearLayoutManager.VERTICAL , false));
//        adapter = new DataAdapter();
        adapter = new DataAdapter2();
        mBinding.listView.setAdapter(adapter);

        mBinding.refreshLayout.setOnRefreshListener(() -> {
            from = 0;
            viewModel.queryDataList(this , keyWord , from);
        });
    }

    private void initData() {
        viewModel.resultDataList.observe(this , dataList->{
            adapter.setNewInstance(dataList);
            if(mBinding.refreshLayout.isRefreshing()){
                mBinding.refreshLayout.setRefreshing(false);
            }

            if(!adapter.getLoadMoreModule().isEnableLoadMore()){
                adapter.getLoadMoreModule().setEnableLoadMore(true);
            }
        });
        viewModel.loadDataList.observe(this , dataList->{
            adapter.addData(dataList);
            adapter.getLoadMoreModule().loadMoreComplete();
        });


        adapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        adapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            from+=20;
            viewModel.loadDataList(this, keyWord , from);
        });
    }

    private void initListener() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        from = 0;
        viewModel.queryDataList(this , keyWord , from);
    }
}